<template>
  <div class="reception-room-bed">
    <div class="header">
      <h2>床位房间管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <div class="content">
      <!-- 房间概览 -->
      <div class="overview-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-icon total-rooms">
                  <el-icon><House /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ roomStats.totalRooms }}</div>
                  <div class="stat-label">总房间数</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-icon occupied-rooms">
                  <el-icon><UserFilled /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ roomStats.occupiedRooms }}</div>
                  <div class="stat-label">已入住房间</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-icon free-rooms">
                  <el-icon><HomeFilled /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ roomStats.freeRooms }}</div>
                  <div class="stat-label">空闲房间</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-icon occupancy-rate">
                  <el-icon><TrendCharts /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ roomStats.occupancyRate }}%</div>
                  <div class="stat-label">入住率</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 房间列表 -->
      <div class="room-section">
        <el-card class="room-card">
          <template #header>
            <div class="card-header">
              <span>房间列表</span>
              <div class="filter-actions">
                <el-select v-model="roomFilter.floor" placeholder="选择楼层" style="width: 120px">
                  <el-option label="全部楼层" value=""></el-option>
                  <el-option v-for="floor in floors" :key="floor" :label="`${floor}层`" :value="floor" />
                </el-select>
                <el-select v-model="roomFilter.roomType" placeholder="房间类型" style="width: 120px">
                  <el-option label="全部类型" value=""></el-option>
                  <el-option label="单人间" value="单人间"></el-option>
                  <el-option label="双人间" value="双人间"></el-option>
                  <el-option label="三人间" value="三人间"></el-option>
                  <el-option label="豪华间" value="豪华间"></el-option>
                </el-select>
                <el-select v-model="roomFilter.status" placeholder="房间状态" style="width: 120px">
                  <el-option label="全部状态" value=""></el-option>
                  <el-option label="空闲" value="空闲"></el-option>
                  <el-option label="已入住" value="已入住"></el-option>
                  <el-option label="维护中" value="维护中"></el-option>
                </el-select>
                <el-button type="primary" @click="loadRooms">搜索</el-button>
              </div>
            </div>
          </template>

          <el-table :data="roomList" v-loading="roomLoading" style="width: 100%">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="roomNumber" label="房间号" width="100" align="center" />
            <el-table-column prop="floor" label="楼层" width="80" align="center">
              <template #default="{ row }">
                {{ row.floor }}层
              </template>
            </el-table-column>
            <el-table-column prop="roomType" label="房间类型" width="100" align="center" />
            <el-table-column prop="bedCount" label="床位数" width="80" align="center" />
            <el-table-column prop="occupiedBeds" label="已用床位" width="80" align="center" />
            <el-table-column prop="freeBeds" label="空闲床位" width="80" align="center" />
            <el-table-column prop="status" label="房间状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getRoomStatusTag(row.status)">
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="dailyRate" label="日租金" width="100" align="center">
              <template #default="{ row }">
                ¥{{ row.dailyRate }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" align="center" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="viewRoomDetail(row)">
                  查看详情
                </el-button>
                <el-button link type="success" @click="viewBeds(row)" v-if="row.freeBeds > 0">
                  查看床位
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="roomPagination.current"
              v-model:page-size="roomPagination.size"
              :total="roomPagination.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleRoomSizeChange"
              @current-change="handleRoomCurrentChange"
            />
          </div>
        </el-card>
      </div>

      <!-- 护工状态 -->
      <div class="caregiver-section">
        <el-card class="caregiver-card">
          <template #header>
            <div class="card-header">
              <span>护工状态</span>
              <div class="filter-actions">
                <el-select v-model="caregiverFilter.status" placeholder="护工状态" style="width: 120px">
                  <el-option label="全部状态" value=""></el-option>
                  <el-option label="在岗" value="在岗"></el-option>
                  <el-option label="休假" value="休假"></el-option>
                  <el-option label="请假" value="请假"></el-option>
                </el-select>
                <el-button type="primary" @click="loadCaregivers">搜索</el-button>
              </div>
            </div>
          </template>

          <el-table :data="caregiverList" v-loading="caregiverLoading">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="name" label="护工姓名" width="100" align="center" />
            <el-table-column prop="phone" label="联系电话" width="120" align="center" />
            <el-table-column prop="title" label="职称" width="100" align="center" />
            <el-table-column prop="level" label="等级" width="80" align="center" />
            <el-table-column prop="elderCount" label="负责老人数" width="100" align="center">
              <template #default="{ row }">
                <span :class="{ 'full-load': row.elderCount >= 5 }">{{ row.elderCount }}/5</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="工作状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getCaregiverStatusTag(row.status)">
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="负责老人" min-width="200" show-overflow-tooltip>
              <template #default="{ row }">
                <div class="elder-list">
                  <span v-for="elder in row.elders" :key="elder.id" class="elder-tag">
                    {{ elder.name }}
                  </span>
                  <span v-if="!row.elders || row.elders.length === 0" class="no-elder">暂无负责老人</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="viewCaregiverDetail(row)">
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="caregiverPagination.current"
              v-model:page-size="caregiverPagination.size"
              :total="caregiverPagination.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleCaregiverSizeChange"
              @current-change="handleCaregiverCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 房间详情对话框 -->
    <el-dialog
      v-model="showRoomDetailDialog"
      title="房间详情"
      width="600px"
    >
      <div class="room-detail" v-if="currentRoom">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>房间号：</label>
              <span>{{ currentRoom.roomNumber }}</span>
            </div>
            <div class="detail-item">
              <label>楼层：</label>
              <span>{{ currentRoom.floor }}层</span>
            </div>
            <div class="detail-item">
              <label>房间类型：</label>
              <span>{{ currentRoom.roomType }}</span>
            </div>
            <div class="detail-item">
              <label>日租金：</label>
              <span>¥{{ currentRoom.dailyRate }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>总床位数：</label>
              <span>{{ currentRoom.bedCount }}</span>
            </div>
            <div class="detail-item">
              <label>已用床位：</label>
              <span>{{ currentRoom.occupiedBeds }}</span>
            </div>
            <div class="detail-item">
              <label>空闲床位：</label>
              <span>{{ currentRoom.freeBeds }}</span>
            </div>
            <div class="detail-item">
              <label>房间状态：</label>
              <el-tag :type="getRoomStatusTag(currentRoom.status)">
                {{ currentRoom.status }}
              </el-tag>
            </div>
          </el-col>
        </el-row>

        <!-- 床位列表 -->
        <div class="bed-list" v-if="currentRoomBeds && currentRoomBeds.length > 0">
          <h4>床位信息</h4>
          <el-table :data="currentRoomBeds" size="small">
            <el-table-column prop="bedNumber" label="床位号" width="80" align="center" />
            <el-table-column prop="status" label="床位状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getBedStatusTag(row.status)" size="small">
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="elderName" label="入住老人" min-width="120" show-overflow-tooltip>
              <template #default="{ row }">
                {{ row.elderName || '空闲' }}
              </template>
            </el-table-column>
            <el-table-column prop="checkinDate" label="入住日期" width="120" align="center">
              <template #default="{ row }">
                {{ row.checkinDate ? formatDate(row.checkinDate) : '-' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <el-button @click="showRoomDetailDialog = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 护工详情对话框 -->
    <el-dialog
      v-model="showCaregiverDetailDialog"
      title="护工详情"
      width="700px"
    >
      <div class="caregiver-detail" v-if="currentCaregiver">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>姓名：</label>
              <span>{{ currentCaregiver.name }}</span>
            </div>
            <div class="detail-item">
              <label>电话：</label>
              <span>{{ currentCaregiver.phone }}</span>
            </div>
            <div class="detail-item">
              <label>职称：</label>
              <span>{{ currentCaregiver.title }}</span>
            </div>
            <div class="detail-item">
              <label>等级：</label>
              <span>{{ currentCaregiver.level }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>工作状态：</label>
              <el-tag :type="getCaregiverStatusTag(currentCaregiver.status)">
                {{ currentCaregiver.status }}
              </el-tag>
            </div>
            <div class="detail-item">
              <label>负责老人数：</label>
              <span>{{ currentCaregiver.elderCount }}/5</span>
            </div>
            <div class="detail-item">
              <label>工作年限：</label>
              <span>{{ currentCaregiver.workYears || 0 }}年</span>
            </div>
            <div class="detail-item">
              <label>入职日期：</label>
              <span>{{ formatDate(currentCaregiver.joinDate) }}</span>
            </div>
          </el-col>
        </el-row>

        <!-- 负责老人列表 -->
        <div class="elder-detail-list" v-if="currentCaregiver.elders && currentCaregiver.elders.length > 0">
          <h4>负责老人列表</h4>
          <el-table :data="currentCaregiver.elders" size="small">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="name" label="老人姓名" width="100" align="center" />
            <el-table-column prop="age" label="年龄" width="80" align="center" />
            <el-table-column prop="gender" label="性别" width="80" align="center" />
            <el-table-column prop="healthStatus" label="健康状况" min-width="120" show-overflow-tooltip />
            <el-table-column prop="bedNumber" label="床位号" width="100" align="center" />
            <el-table-column prop="roomNumber" label="房间号" width="100" align="center" />
          </el-table>
        </div>
        <div v-else class="no-data">
          <el-empty description="暂无负责老人" />
        </div>
      </div>

      <template #footer>
        <el-button @click="showCaregiverDetailDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, House, UserFilled, HomeFilled, TrendCharts } from '@element-plus/icons-vue'
import { getAllRooms, getRoomBeds, getCaregivers } from '@/api/room-bed'

const loading = ref(false)
const roomLoading = ref(false)
const caregiverLoading = ref(false)
const showRoomDetailDialog = ref(false)
const showCaregiverDetailDialog = ref(false)

// 房间数据
const roomList = ref([])
const currentRoom = ref(null)
const currentRoomBeds = ref([])

// 护工数据
const caregiverList = ref([])
const currentCaregiver = ref(null)

// 楼层选项
const floors = ref([1, 2, 3, 4, 5, 6])

// 房间统计
const roomStats = reactive({
  totalRooms: 0,
  occupiedRooms: 0,
  freeRooms: 0,
  occupancyRate: 0
})

// 筛选条件
const roomFilter = reactive({
  floor: '',
  roomType: '',
  status: ''
})

const caregiverFilter = reactive({
  status: ''
})

// 分页
const roomPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const caregiverPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取房间状态标签类型
const getRoomStatusTag = (status) => {
  const statusMap = {
    '空闲': 'success',
    '已入住': 'primary',
    '维护中': 'warning'
  }
  return statusMap[status] || 'info'
}

// 获取护工状态标签类型
const getCaregiverStatusTag = (status) => {
  const statusMap = {
    '在岗': 'success',
    '休假': 'warning',
    '请假': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取床位状态标签类型
const getBedStatusTag = (status) => {
  const statusMap = {
    '空闲': 'success',
    '已入住': 'primary',
    '维护中': 'warning'
  }
  return statusMap[status] || 'info'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 加载房间数据
const loadRooms = async () => {
  roomLoading.value = true
  try {
    const params = {
      page: roomPagination.current,
      size: roomPagination.size,
      ...roomFilter
    }
    const response = await getAllRooms(params)
    if (response.code === 200) {
      roomList.value = response.data.records || []
      roomPagination.total = response.data.total || 0
      
      // 计算房间统计
      calculateRoomStats()
    } else {
      ElMessage.error(response.msg || '加载房间数据失败')
    }
  } catch (error) {
    console.error('加载房间数据失败:', error)
    ElMessage.error('加载房间数据失败')
  } finally {
    roomLoading.value = false
  }
}

// 计算房间统计信息
const calculateRoomStats = () => {
  const rooms = roomList.value
  roomStats.totalRooms = rooms.length
  roomStats.occupiedRooms = rooms.filter(room => room.status === '已入住').length
  roomStats.freeRooms = rooms.filter(room => room.status === '空闲').length
  roomStats.occupancyRate = roomStats.totalRooms > 0 
    ? Math.round((roomStats.occupiedRooms / roomStats.totalRooms) * 100)
    : 0
}

// 加载护工数据
const loadCaregivers = async () => {
  caregiverLoading.value = true
  try {
    const params = {
      page: caregiverPagination.current,
      size: caregiverPagination.size,
      ...caregiverFilter
    }
    const response = await getCaregivers(params)
    if (response.code === 200) {
      caregiverList.value = response.data.records || []
      caregiverPagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '加载护工数据失败')
    }
  } catch (error) {
    console.error('加载护工数据失败:', error)
    ElMessage.error('加载护工数据失败')
  } finally {
    caregiverLoading.value = false
  }
}

// 查看房间详情
const viewRoomDetail = async (room) => {
  currentRoom.value = room
  try {
    const response = await getRoomBeds(room.id)
    if (response.code === 200) {
      currentRoomBeds.value = response.data || []
    } else {
      currentRoomBeds.value = []
      ElMessage.error(response.msg || '加载床位信息失败')
    }
  } catch (error) {
    console.error('加载床位信息失败:', error)
    currentRoomBeds.value = []
    ElMessage.error('加载床位信息失败')
  }
  showRoomDetailDialog.value = true
}

// 查看床位
const viewBeds = (room) => {
  // 这里可以跳转到床位管理页面或显示床位详情
  ElMessage.info(`查看房间 ${room.roomNumber} 的床位信息`)
}

// 查看护工详情
const viewCaregiverDetail = (caregiver) => {
  currentCaregiver.value = caregiver
  showCaregiverDetailDialog.value = true
}

// 刷新数据
const refreshData = () => {
  loadRooms()
  loadCaregivers()
}

// 分页处理
const handleRoomSizeChange = (size) => {
  roomPagination.size = size
  roomPagination.current = 1
  loadRooms()
}

const handleRoomCurrentChange = (current) => {
  roomPagination.current = current
  loadRooms()
}

const handleCaregiverSizeChange = (size) => {
  caregiverPagination.size = size
  caregiverPagination.current = 1
  loadCaregivers()
}

const handleCaregiverCurrentChange = (current) => {
  caregiverPagination.current = current
  loadCaregivers()
}

// 组件挂载时加载数据
onMounted(() => {
  loadRooms()
  loadCaregivers()
})
</script>

<style scoped>
.reception-room-bed {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.overview-section {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
}

.stat-item {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stat-icon.total-rooms {
  background-color: #409EFF;
}

.stat-icon.occupied-rooms {
  background-color: #67C23A;
}

.stat-icon.free-rooms {
  background-color: #E6A23C;
}

.stat-icon.occupancy-rate {
  background-color: #F56C6C;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.elder-list {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.elder-tag {
  background-color: #f0f9ff;
  border: 1px solid #409EFF;
  border-radius: 4px;
  padding: 2px 6px;
  font-size: 12px;
  color: #409EFF;
}

.no-elder {
  color: #909399;
  font-size: 12px;
}

.full-load {
  color: #F56C6C;
  font-weight: bold;
}

.room-detail,
.caregiver-detail {
  padding: 10px 0;
}

.detail-item {
  display: flex;
  margin-bottom: 15px;
  align-items: center;
}

.detail-item label {
  width: 80px;
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
}

.detail-item span {
  flex: 1;
  color: #303133;
}

.bed-list,
.elder-detail-list {
  margin-top: 20px;
}

.bed-list h4,
.elder-detail-list h4 {
  margin-bottom: 15px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.no-data {
  text-align: center;
  padding: 40px 0;
}
</style>
